#!/usr/bin/env python3
"""
路由数据初始化脚本
将现有硬编码的路由配置迁移到数据库中
"""

import asyncio
import sys
import os
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_db, engine
from app.models.auth import Route, Permission, RoutePermission, User
from app.utils.timezone_utils import get_shanghai_now
from sqlalchemy import select, and_
from datetime import datetime


# 系统路由配置数据
SYSTEM_ROUTES = [
    {
        'path': '/',
        'name': 'dashboard',
        'display_name': '仪表盘',
        'description': '系统概览和统计信息',
        'icon': 'DashboardOutlined',
        'component': 'Dashboard',
        'is_menu': True,
        'sort_order': 1,
        'permissions': []  # 仪表盘无需特殊权限
    },
    {
        'path': '/lineage',
        'name': 'lineage',
        'display_name': '数据血缘',
        'description': '数据血缘关系图谱',
        'icon': 'TableOutlined',
        'component': 'DataLineage',
        'is_menu': True,
        'sort_order': 2,
        'permissions': ['lineage.view']
    },
    {
        'path': '/system',
        'name': 'system',
        'display_name': '系统管理',
        'description': '系统管理功能',
        'icon': 'SettingOutlined',
        'component': None,
        'is_menu': True,
        'sort_order': 3,
        'permissions': [],
        'children': [
            {
                'path': '/users',
                'name': 'users',
                'display_name': '用户管理',
                'description': '系统用户管理',
                'icon': 'UserOutlined',
                'component': 'UserManagement',
                'is_menu': True,
                'sort_order': 1,
                'permissions': ['user.view']
            },
            {
                'path': '/roles',
                'name': 'roles',
                'display_name': '角色管理',
                'description': '系统角色管理',
                'icon': 'TeamOutlined',
                'component': 'RoleManagement',
                'is_menu': True,
                'sort_order': 2,
                'permissions': ['role.view']
            },
            {
                'path': '/permissions',
                'name': 'permissions',
                'display_name': '权限管理',
                'description': '系统权限管理',
                'icon': 'SafetyOutlined',
                'component': 'PermissionManagement',
                'is_menu': True,
                'sort_order': 3,
                'permissions': ['permission.view', 'role.create', 'role.update', 'role.delete']
            },
            {
                'path': '/routes',
                'name': 'routes',
                'display_name': '路由管理',
                'description': '系统路由配置管理',
                'icon': 'BranchesOutlined',
                'component': 'RouteManagement',
                'is_menu': True,
                'sort_order': 4,
                'permissions': ['route.view', 'route.manage']
            },
        ]
    },
    {
        'path': '/showcase',
        'name': 'showcase',
        'display_name': 'UI展示',
        'description': 'UI组件展示页面',
        'icon': 'AppstoreOutlined',
        'component': 'UIShowcase',
        'is_menu': True,
        'sort_order': 7,
        'permissions': []  # 展示页面无需特殊权限
    },
    {
        'path': '/login',
        'name': 'login',
        'display_name': '登录',
        'description': '用户登录页面',
        'icon': '',
        'component': 'Login',
        'is_menu': False,
        'sort_order': 100,
        'permissions': []  # 登录页面无需权限
    }
]


async def create_route_permissions():
    """创建路由管理相关的权限"""
    async with AsyncSession(engine) as db:
        try:
            # 检查是否已存在路由管理权限
            stmt = select(Permission).where(Permission.name.in_(['route.view', 'route.manage']))
            result = await db.execute(stmt)
            existing_permissions = result.scalars().all()
            existing_names = {p.name for p in existing_permissions}
            
            # 创建缺失的权限
            new_permissions = []
            if 'route.view' not in existing_names:
                new_permissions.append(Permission(
                    name='route.view',
                    display_name='查看路由',
                    description='查看系统路由配置',
                    resource='route',
                    action='view',
                    is_system=True
                ))
            
            if 'route.manage' not in existing_names:
                new_permissions.append(Permission(
                    name='route.manage',
                    display_name='管理路由',
                    description='管理系统路由配置',
                    resource='route',
                    action='manage',
                    is_system=True
                ))
            
            if new_permissions:
                db.add_all(new_permissions)
                await db.commit()
                print(f"✅ 创建了 {len(new_permissions)} 个路由管理权限")
            else:
                print("✅ 路由管理权限已存在")
                
        except Exception as e:
            print(f"❌ 创建路由管理权限失败: {e}")
            await db.rollback()
            raise


async def create_or_update_route(db: AsyncSession, route_data: dict, parent_id: int = None) -> tuple:
    """创建或更新路由（递归处理子路由）"""
    created_count = 0
    updated_count = 0

    # 检查路由是否已存在
    stmt = select(Route).where(Route.path == route_data['path'])
    result = await db.execute(stmt)
    existing_route = result.scalar_one_or_none()

    if existing_route:
        # 更新现有路由
        existing_route.name = route_data['name']
        existing_route.display_name = route_data['display_name']
        existing_route.description = route_data['description']
        existing_route.icon = route_data['icon']
        existing_route.component = route_data['component']
        existing_route.is_menu = route_data['is_menu']
        existing_route.sort_order = route_data['sort_order']
        existing_route.is_system = True
        existing_route.parent_id = parent_id
        existing_route.updated_at = get_shanghai_now()
        route = existing_route
        updated_count += 1
    else:
        # 创建新路由
        route = Route(
            path=route_data['path'],
            name=route_data['name'],
            display_name=route_data['display_name'],
            description=route_data['description'],
            icon=route_data['icon'],
            component=route_data['component'],
            parent_id=parent_id,
            is_menu=route_data['is_menu'],
            sort_order=route_data['sort_order'],
            is_system=True,
            is_active=True
        )
        db.add(route)
        created_count += 1

    # 提交更改以获取路由ID
    await db.commit()
    # 重新查询以获取完整的路由对象
    if not existing_route:
        stmt = select(Route).where(Route.path == route_data['path'])
        result = await db.execute(stmt)
        route = result.scalar_one()

    # 处理权限关联（暂时跳过，后续手动配置）
    if route_data['permissions']:
        print(f"📝 路由 '{route.path}' 需要权限: {route_data['permissions']}")

    # 递归处理子路由
    if 'children' in route_data and route_data['children']:
        for child_data in route_data['children']:
            child_created, child_updated = await create_or_update_route(db, child_data, route.id)
            created_count += child_created
            updated_count += child_updated

    return created_count, updated_count


async def init_routes():
    """初始化系统路由数据"""
    async with AsyncSession(engine) as db:
        try:
            print("🚀 开始初始化系统路由数据...")

            # 获取系统管理员用户（用于创建记录）
            stmt = select(User).where(User.username == 'admin')
            result = await db.execute(stmt)
            admin_user = result.scalar_one_or_none()

            if not admin_user:
                print("❌ 未找到管理员用户，请先初始化用户数据")
                return

            # 获取所有权限的映射
            stmt = select(Permission)
            result = await db.execute(stmt)
            all_permissions = result.scalars().all()
            permission_map = {p.name: p for p in all_permissions}

            total_created = 0
            total_updated = 0
            
            for route_data in SYSTEM_ROUTES:
                created, updated = await create_or_update_route(db, route_data)
                total_created += created
                total_updated += updated

            print(f"✅ 路由初始化完成: 创建 {total_created} 个，更新 {total_updated} 个")
            
        except Exception as e:
            print(f"❌ 初始化路由数据失败: {e}")
            await db.rollback()
            raise


async def main():
    """主函数"""
    try:
        print("🔧 DataPlexus 路由数据初始化")
        print("=" * 50)
        
        # 创建路由管理权限
        await create_route_permissions()
        
        # 初始化路由数据
        await init_routes()
        
        print("=" * 50)
        print("🎉 路由数据初始化完成！")
        
    except Exception as e:
        print(f"❌ 初始化失败: {e}")
        sys.exit(1)


if __name__ == "__main__":
    asyncio.run(main())
